<?php
/**
 * *
 *  * ============================================================================
 *  * Created by PhpStorm.
 *  * User: Ice
 *  * 邮箱: ice@sbing.vip
 *  * 网址: https://sbing.vip
 *  * Date: 2019/9/19 下午3:33
 *  * ============================================================================.
 */

namespace app\admin\command;

use app\common\service\RedisMake;
use think\console\Input;
use think\facade\Config;
use think\console\Output;
use think\console\Command;


class Swoole extends Command
{

    public static $SUCCESS_CODE = 200;
    public static $ERROR_CODE = -1;

    protected function configure()
    {
        $site = Config::get('site');
        $this
            ->setName('swoole')
            ->setDescription('Build swoole from controller');
    }

    protected function execute(Input $input, Output $output)
    {
        $config = config('swoole.');
        $server = new \Swoole\WebSocket\Server("0.0.0.0", $config['swoole_host']??9501);
        $server->set(array(
            'reactor_num'   => $config['reactor_num']??2,     // reactor thread num
            'worker_num'    => $config['worker_num']??4,     // worker process num
            'backlog'       => $config['backlog']??128,   // listen backlog
            'max_request'   => $config['max_request']??50,
            'daemonize'     => $config['daemonize']??false,
        ));
        $server->on('open', function (\Swoole\WebSocket\Server $server, $request) {
        });

        $server->on('message', function (\Swoole\WebSocket\Server $server, $frame) {
            $data = json_decode($frame->data,true);
            $result = swoole_error("参数不正确1！");
            //系统消息
            if(isset($data['action']) && $data['action'] == "system_send_message"){
                $result = swoole_success($data['message']);
                $server->push($data['fd'], $result);
            }else{
				do{
                if(!$data){
                    $result = swoole_error("参数不正确2！");
                    break;
                }

                $game = $data['game']??"";
                if(!$game){
                    $result = swoole_error("参数不正确3！");
                    break;
                }
                $class = "app\common\\service\\".$game."\\Index";
                //引用对应游戏类
                if(!class_exists($class)){
                    $result = swoole_error("参数不正确4！".$class);
                    break;
                }
                $service = new $class($this->app);
                if(!method_exists($service,"index")){
                    $result = swoole_error("参数不正确5！");
                    break;
                }
                $result = $service->index($data,$frame->fd);
            }while(0);
				$server->push($frame->fd, $result);
			}
        });

		$server->on('request', function (\Swoole\Http\Request $request, \Swoole\Http\Response $response)use($server) {
            $code = 400;
            do{
                $data = $request->post;
                if(!$data){
                    break;
                }
                if(!isset($data['action']) || $data['action'] != "system_send_message"){
                    break;
                }
                $message = $data['message']??"";
                $fd = $data['fd']??0;
                if(!$message || !$fd){
                    break;
                }
                $res = $server->push($fd, $message);
                $code = 200;
                $result = "发送成功！";
            }while(0);
            $response->status($code);
			if($code != 400){
                $response->end($result);
            }
		});

        $server->on('close', function ($ser, $fd) {
            $this->closeFd($fd);
            //查询是否在房间里 在的话要退出
        });

        $server->start();
    }

    //退出房间
    public function closeFd($fd){
        $redis = RedisMake::getRedis();
        $roomData =$redis->hExists('user_game', $fd);
        if($roomData){
            $roomData =$redis->hGet('user_game', $fd);
            $roomData = json_decode($roomData,true);
            if(!$roomData){
                //写日志
                return;
            }
            //$redis->hDel('user_game', $fd);
            $game = $roomData['type']??"";
            if(!$game){
                //写日志);
                return;
            }
            $class = "app\common\\service\\".$game."\\Index";
            //引用对应游戏类
            if(!class_exists($class)){
                //写日志
                return;
            }
            $service = new $class($this->app);
            if(!method_exists($service,"index")){
                //写日志
                return;
            }
            $result = $service->index($roomData,$fd,"close");
        }
    }

}
